package modes

import (
	"fmt"
	"time"
)

type StudentInfo struct {
	Id      int64  `json:"stu_id"`                     // 学员ID
	Phone   int64  `json:"stu_phone" xorm:"phone"`     // 手机号
	Pass    string `json:"-" xorm:"pass"`              // 密码
	Name    string `json:"stu_name" xorm:"name"`       // 学员姓名
	At      int64  `json:"stu_at" xorm:"at"`           // 第一次登陆时间
	LastAt  int64  `json:"stu_last_at" xorm:"last_at"` // 最后一次登陆时间
	Coun    int64  `json:"stu_coun" xorm:"coun"`       // 登陆次数
	File    string `json:"stu_file" xorm:"file"`       // 头像
	Email   string `json:"stu_email" xorm:"email"`     // 邮箱
	Address string `json:"stu_address" xorm:"address"` // 地址
	Start   int    `json:"stu_start" xorm:"start"`     //状态
	Col     int64  `json:"stu_col" xorm:"col"`         //学习时长
	DayCo   int64  `json:"stu_day_co" xorm:"dayco"`	   //连续听课天数
	Rat		int64  `json:"stu_rat" xorm:"rat"` 		   //当天听课第一次时间
	//ALTER TABLE studen_info ADD dayco int unsigned   NOT NULL DEFAULT 0;  -- 连续听课天数
	//ALTER TABLE studen_info ADD rat int unsigned   NOT NULL DEFAULT 0;  -- 当天听课第一次时间
}

func (this *StudentInfo) TableName() string {
	return "studen_info"
}
func (this *StudentInfo) Save() (int64, error) {
	this.At = time.Now().Unix()
	this.Start = 0
	return Db(0).Insert(this)
}

func (this *StudentInfo) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *StudentInfo) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *StudentInfo) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *StudentInfo) Count(where string) (int64, error) {
	var val StudentInfo
	return Db(0).Where(where).Count(&val)
}
func (this *StudentInfo) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *StudentInfo) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *StudentInfo) where(fage, count, page int, where, field string) ([]CrmStuden, error) {
	list := make([]CrmStuden, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *StudentInfo) List(val *Pager) error {
	val.TName = this.TableName()
	val.Total, _ = this.Count(val.ToWhere())
	list, err := this.where(val.Rules, val.Count, val.Page-1, val.ToWhere(), "")
	if err == nil {
		val.List = list
	}
	return err
}

func (this *StudentInfo) Lists(id string) ([]StudentInfo, error) {
	list := make([]StudentInfo, 0)
	var err error
	err = Db(0).Table("studen_info").
		Where("id = ?", id).
		Find(&list)
	return list, err
}
